package main

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
)

const (
	filename = "card_url.txt"
)

func getFileByUrl(url string) (data []byte, err error) {
	resp, err := http.Get(url)
	if err != nil {
		return data, err
	}
	defer resp.Body.Close()

	data, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		return data, err
	}

	//ioutil.WriteFile("./pic/1.png", data, 0644)
	//fmt.Println(string(data))
	return data, err
}

func main() {
	file, err := os.Open(filename)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	reader := bufio.NewReader(file)

	for {
		line, _, err := reader.ReadLine()
		if err == io.EOF {
			break
		}
		url := string(line)
		png := strings.Split(url, "/")
		pngName := png[len(png)-1]
		raceInfo := strings.Split(pngName, "_")
		race := "./pic/" + raceInfo[0]
		fmt.Println(race, pngName)
		_, err = os.Stat(race)
		if err != nil {
			if !os.IsExist(err) {
				os.Mkdir(race, os.ModePerm)
			} else {
				panic(err)
			}
		}
		result, err := getFileByUrl(url)
		if err != nil {
			continue
		}
		ioutil.WriteFile(race+"/"+pngName, result, 0644)
	}
	return

}
